package com.liuyjy.exception.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liuyjy.core.enums.ResultCodeEnum;
import com.liuyjy.core.exception.AppException;
import com.liuyjy.core.exception.BaseException;
import com.liuyjy.utils.utils.EmptyUtil;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author liuyjy
 * @Date 2022/2/8 12:38
 * @Description: feign 调用异常管理
 **/
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {
    private static final String ERROR_MESSAGE = "Load balancer does not contain an instance for the service";

    @Override
    public Exception decode(String methodKey, Response response) {
        BaseException exception = new AppException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
        try {
            Response.Body body = response.body();
            String rsb = Util.toString(body.asReader(Util.UTF_8));
            if(rsb.contains(ERROR_MESSAGE)){
                return new AppException(ResultCodeEnum.NOT_IMPLEMENTED);
            }
            JSONObject jsonObject = null;
            try {
                jsonObject = JSON.parseObject(rsb);
            } catch (Exception e) {
                log.error("{}调用异常:{}", methodKey, rsb);
                return exception;
            }
            try {
                String code = jsonObject.getString("code");
                String msg = jsonObject.getString("msg");
                if (!EmptyUtil.isEmpty(code)) {
                    exception = new BaseException(code, msg);
                }
            } catch (Exception var7) {
                var7.printStackTrace();
                // exception = new AppException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
            }
        } catch (IOException var8) {
            var8.printStackTrace();
            //exception = new AppException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
        }
        log.error("{}调用异常:{}", methodKey, exception.toString());
        return exception;
    }


}
